/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package api.user;

import Model.User.UserList;
import RssEasy.Core.CookieHelper;
import RssEasy.Core.Encrypt;
import RssEasy.Core.HttpRequestHelper;
import RssEasy.Core.ServletRequestHelper;
import RssEasy.Core.SignVerifyRequestHelper;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author zhangwenbo
 */
@WebServlet(name = "api_user_login", urlPatterns = {"/api/user/login"})
public class login extends ServletRequestHelper {

    @Override
    protected HttpRequestHelper request(HttpServletRequest request, HttpServletResponse response) {
        super.request(request, response);
        try {
            UserList list = new UserList(this.pageContext);
            UserList use = new UserList(this.pageContext);
            list.request();
            use.request();
            String enterprise = this.get("enterprise").toLowerCase();
            String account = this.get("account").toLowerCase();
            String pwd = this.get("pwd").toLowerCase();
            String Encryption = account + pwd;
            if (!list.select().where("account=?", account).get_first_rows()) {
                throw new Exception("100");
            }
            if (!list.select().where("enterprise=?", enterprise).get_first_rows()) {
                throw new Exception("102");
            }
            if (list.select().where("enterprise='" + enterprise + "' and account='" + account + "' and pwd='" + Encrypt.Md532(Encryption) + "'").get_first_rows()) {
                use.select("account,parentmyid,myid").where("enterprise='" + enterprise + "' and account='" + account + "' and pwd='" + Encrypt.Md532(Encryption) + "'").get_first_rows();
                CookieHelper cookie = new CookieHelper(request, response);
                if (use.get("selected").length() > 0) {
                    cookie.Set("learn", "ok", 7);
                }
                out.print(use.toKeyValue());
            } else {
                throw new Exception("101");
            }
        } catch (Exception e) {
            out.print("{\"rsscode\":" + e.getMessage() + "}");
        }
        return this;
    }
}
